package com.wuxi.zhang.jiguang;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static cn.jpush.api.push.model.notification.PlatformNotification.ALERT;


/**
 * 极光推送模板
 *
 * @author zhang on 2019/3/21.
 */
@Slf4j
@RestController
public class PushExample {

    public static final String MASTER_SECRET = "4c59cb313ebef8a415d0967b";

    public static final String APP_KEY = "e39c17ca69ee7f3a457865fa";

    JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());

    @RequestMapping("/push/test")
    public void testPush() {

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_all_alert();

        try {
            PushResult result = jpushClient.sendPush(payload);
            log.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
    }

    /**
     * 通过使用标签，别名，Registration ID 和用户分群，开发者可以向特定的一个或多个用户推送消息。
     *
     * @return
     */
    private static PushPayload buildPushObject_all_all_alert() {
        //return PushPayload.newBuilder()
        //                .setPlatform(Platform.all())
        //                .setAudience(Audience.alias("alias1"))
        //                .setNotification(Notification.alert(ALERT))
        //        .build();
        return PushPayload.alertAll(ALERT);
    }


}
